<!--
  API统计图表组件
  @description API调用量和成功率趋势图表
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <div class="api-statistics">
    <!-- 图表切换标签 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane :label="t('sop.statistics.callsChart')" name="calls">
        <div ref="callsChartRef" class="chart-container" v-loading="chartLoading"></div>
      </el-tab-pane>
      <el-tab-pane :label="t('sop.statistics.successRateChart')" name="successRate">
        <div ref="successRateChartRef" class="chart-container" v-loading="chartLoading"></div>
      </el-tab-pane>
      <el-tab-pane :label="t('sop.statistics.responseTimeChart')" name="responseTime">
        <div ref="responseTimeChartRef" class="chart-container" v-loading="chartLoading"></div>
      </el-tab-pane>
    </el-tabs>

    <!-- 详细数据表格 -->
    <div class="mt-20px">
      <el-table :data="tableData" v-loading="tableLoading" border>
        <el-table-column :label="t('sop.statistics.apiPath')" prop="apiPath" min-width="200" />
        <el-table-column :label="t('sop.statistics.totalCalls')" prop="totalCalls" width="120" align="center">
          <template #default="scope">
            <el-tag type="primary">{{ formatNumber(scope.row.totalCalls) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.successCalls')" prop="successCalls" width="120" align="center">
          <template #default="scope">
            <el-tag type="success">{{ formatNumber(scope.row.successCalls) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.errorCalls')" prop="errorCalls" width="120" align="center">
          <template #default="scope">
            <el-tag type="danger">{{ formatNumber(scope.row.errorCalls) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.successRate')" prop="successRate" width="120" align="center">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.successRate" 
              :color="getSuccessRateColor(scope.row.successRate)"
              :show-text="false"
              style="width: 80px"
            />
            <span class="ml-8px">{{ scope.row.successRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.avgResponseTime')" prop="avgResponseTime" width="140" align="center">
          <template #default="scope">
            <span :class="getResponseTimeClass(scope.row.avgResponseTime)">
              {{ scope.row.avgResponseTime }}ms
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { getApiStatisticsApi } from '@/api/sop/statistics'
import type { ApiStatisticsVO } from '@/api/sop/types'

defineOptions({ name: 'ApiStatistics' })

const { t } = useI18n()

// Props
const props = defineProps<{
  dateRange: string[]
  loading: boolean
}>()

// Emits
const emit = defineEmits<{
  loadingChange: [loading: boolean]
}>()

// 响应式数据
const activeTab = ref('calls')
const chartLoading = ref(false)
const tableLoading = ref(false)
const tableData = ref<ApiStatisticsVO[]>([])

// 图表引用
const callsChartRef = ref<HTMLDivElement>()
const successRateChartRef = ref<HTMLDivElement>()
const responseTimeChartRef = ref<HTMLDivElement>()

// 图表实例
let callsChart: ECharts | null = null
let successRateChart: ECharts | null = null
let responseTimeChart: ECharts | null = null

// 图表数据
const chartData = ref({
  dates: [] as string[],
  callsData: [] as number[],
  successRateData: [] as number[],
  responseTimeData: [] as number[]
})

/**
 * 获取API统计数据
 */
const getApiStatistics = async () => {
  if (!props.dateRange || props.dateRange.length !== 2) return
  
  chartLoading.value = true
  tableLoading.value = true
  emit('loadingChange', true)
  
  try {
    const data = await getApiStatisticsApi({
      startTime: props.dateRange[0],
      endTime: props.dateRange[1]
    })
    
    // 处理图表数据
    chartData.value = {
      dates: data.trendData.map(item => item.date),
      callsData: data.trendData.map(item => item.totalCalls),
      successRateData: data.trendData.map(item => item.successRate),
      responseTimeData: data.trendData.map(item => item.avgResponseTime)
    }
    
    // 处理表格数据
    tableData.value = data.apiList
    
    // 更新图表
    await nextTick()
    updateCharts()
  } catch (error) {
    console.error('获取API统计数据失败:', error)
  } finally {
    chartLoading.value = false
    tableLoading.value = false
    emit('loadingChange', false)
  }
}

/**
 * 初始化图表
 */
const initCharts = () => {
  if (callsChartRef.value) {
    callsChart = echarts.init(callsChartRef.value)
  }
  if (successRateChartRef.value) {
    successRateChart = echarts.init(successRateChartRef.value)
  }
  if (responseTimeChartRef.value) {
    responseTimeChart = echarts.init(responseTimeChartRef.value)
  }
}

/**
 * 更新图表
 */
const updateCharts = () => {
  // 调用量图表
  if (callsChart) {
    const option = {
      title: {
        text: t('sop.statistics.apiCallsTrend'),
        left: 'center',
        textStyle: { fontSize: 14 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
      },
      xAxis: {
        type: 'category',
        data: chartData.value.dates,
        axisLabel: { rotate: 45 }
      },
      yAxis: {
        type: 'value',
        name: t('sop.statistics.callsCount')
      },
      series: [{
        name: t('sop.statistics.apiCalls'),
        type: 'bar',
        data: chartData.value.callsData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }],
      grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }
    }
    callsChart.setOption(option)
  }

  // 成功率图表
  if (successRateChart) {
    const option = {
      title: {
        text: t('sop.statistics.successRateTrend'),
        left: 'center',
        textStyle: { fontSize: 14 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
        formatter: '{b}<br/>{a}: {c}%'
      },
      xAxis: {
        type: 'category',
        data: chartData.value.dates,
        axisLabel: { rotate: 45 }
      },
      yAxis: {
        type: 'value',
        name: t('sop.statistics.successRate') + '(%)',
        min: 0,
        max: 100
      },
      series: [{
        name: t('sop.statistics.successRate'),
        type: 'line',
        data: chartData.value.successRateData,
        smooth: true,
        lineStyle: { color: '#67c23a', width: 3 },
        itemStyle: { color: '#67c23a' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ])
        }
      }],
      grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }
    }
    successRateChart.setOption(option)
  }

  // 响应时间图表
  if (responseTimeChart) {
    const option = {
      title: {
        text: t('sop.statistics.responseTimeTrend'),
        left: 'center',
        textStyle: { fontSize: 14 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
        formatter: '{b}<br/>{a}: {c}ms'
      },
      xAxis: {
        type: 'category',
        data: chartData.value.dates,
        axisLabel: { rotate: 45 }
      },
      yAxis: {
        type: 'value',
        name: t('sop.statistics.responseTime') + '(ms)'
      },
      series: [{
        name: t('sop.statistics.avgResponseTime'),
        type: 'line',
        data: chartData.value.responseTimeData,
        smooth: true,
        lineStyle: { color: '#e6a23c', width: 3 },
        itemStyle: { color: '#e6a23c' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
            { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
          ])
        }
      }],
      grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true }
    }
    responseTimeChart.setOption(option)
  }
}

/**
 * 标签页切换
 */
const handleTabChange = async () => {
  await nextTick()
  resizeCharts()
}

/**
 * 调整图表大小
 */
const resizeCharts = () => {
  callsChart?.resize()
  successRateChart?.resize()
  responseTimeChart?.resize()
}

/**
 * 格式化数字
 */
const formatNumber = (num: number) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 获取成功率颜色
 */
const getSuccessRateColor = (rate: number) => {
  if (rate >= 95) return '#67c23a'
  if (rate >= 90) return '#e6a23c'
  return '#f56c6c'
}

/**
 * 获取响应时间样式类
 */
const getResponseTimeClass = (time: number) => {
  if (time < 100) return 'fast-response'
  if (time < 500) return 'normal-response'
  if (time < 1000) return 'slow-response'
  return 'very-slow-response'
}

// 监听日期范围变化
watch(() => props.dateRange, () => {
  getApiStatistics()
}, { deep: true })

// 组件挂载
onMounted(async () => {
  await nextTick()
  initCharts()
  getApiStatistics()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts)
})

// 组件卸载
onUnmounted(() => {
  callsChart?.dispose()
  successRateChart?.dispose()
  responseTimeChart?.dispose()
  window.removeEventListener('resize', resizeCharts)
})
</script>

<style scoped>
.api-statistics {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.mt-20px {
  margin-top: 20px;
}

.ml-8px {
  margin-left: 8px;
}

.fast-response {
  color: #67c23a;
  font-weight: bold;
}

.normal-response {
  color: #409eff;
}

.slow-response {
  color: #e6a23c;
  font-weight: bold;
}

.very-slow-response {
  color: #f56c6c;
  font-weight: bold;
}
</style>
